<template>
  <div class='footbox' v-if="vals.length">
    <!-- <p class="tips" v-if="showCounter">因赔率随时变动，请与终端机赔率核对，最终结果以出票为准！</p> -->
    <div class="selectBar" v-if="showCounter">
      <p>已选<span class="amt">{{ isDg1Tips }}</span>场比赛</p>
      <div class="block" @click="openGgHandle()">
        <span class="label">过关</span>
        <div class="ggBox">
          <span>{{ gG.firstText }}</span>
          <van-icon name="play" size="14px" color="#b4b4b4" />
        </div>
      </div>
      <div class="block">
        <span class="label">倍数</span>
        <div class="multiBox">
          <div class="sub" @click="changeMulti('-')">-</div>
          <van-field v-model="multiNum" type="digit" class="multIpt" @update:model-value="changeMulti" />
          <div class="plus" @click="changeMulti('+')">+</div>
        </div>
      </div>
    </div>
    <div class="counterBar" v-if="showCounter">
      <div class="left">
        <p>金额：<span class="amt">{{ betAmt }}元</span></p>
        <p class="fz20" @click="openBonusTest">预计最高奖金：<span class="amt maxBonus">{{ Number(maxBonus).toFixed(2)
            }}元</span></p>
      </div>
      <div class="btns">
        <!-- 奖金优化暂时先不迁移 -->
        <!-- <div class="bonusOpt" @click="bonusOpt" v-if="canOpt">奖金优化<van-icon name="arrow" size="14px" /></div> -->
        <van-button plain color="#aaa" @click='goResetData()'>重选</van-button>
        <van-button color="linear-gradient(to right, #fe673a 0%, #fd9316 100%)" @click="gotoPoster">确定</van-button>
      </div>
    </div>
    <div class='confirm' v-else>
      <!-- <div class='left' @click='goResetData()'>重选</div> -->
      <div class='center' v-html="isDg1Tips"></div>
      <!-- <div class='right' @click='goToRaceColor()'>确定</div> -->
    </div>
  </div>
  <!-- 串关定胆 - 弹出层 -->
  <van-overlay :show="showChuanPop" :lock-scroll="false" :custom-style="{background: 'rgba(0, 0, 0, 0.3)'}"
    z-index="999">
    <div class="pop fixedBottomPop">
      <van-icon name="close" color="#1d2129" class="closeBtn" @click="showChuanPop = false" />
      <div class="tabs">
        <div :class="['tab', { 'act': !selectedTab }]" @click="selectedTab = 0">过关方式</div>
        <div :class="['tab', { 'act': selectedTab }]" @click="selectedTab = 1">
          <van-badge :content="dans.length" v-if="dans.length">设胆</van-badge>
          <span v-else>设胆</span>
        </div>
      </div>
      <div class="ggWay scrollArea" v-if="!selectedTab">
        <div :class="['gg', { 'act': gG.selectChuans.includes(item.v)}]" v-for="item in chuanFilter" :key="item.v"
          @click="chuanHandle(item.v)">{{item.t}}</div>
        <p class="title">更多过关<span class="tip">(不支持定胆)</span></p>
        <div :class="['gg', { 'act': gG.selectChuans.includes(item.v) }]" v-for="item in chuanMoreFilter" :key="item.v"
          @click="chuanHandle(item.v)">{{item.t}}</div>
      </div>
      <div class="setDanList scrollArea" v-else>
        <div class="li" v-for="(match, i) in vals" :key="i">
          <!-- <van-icon name="cross" class="delete" /> -->
          <div class="matchDetail">
            <p class="tit">{{`${match[0].week}${match[0].weekno} ${match[0].home} VS ${match[0].guest}`}}
            </p>
            <van-tag color="#F96235" v-for="(pm,k) in match" :key="k">{{ pm.result + pm.odds}}</van-tag>
          </div>
          <div :class="['setup', { 'act': dans.includes(match[0].weekNum)}]" @click="danHandle(match[0].weekNum)">胆
          </div>
        </div>
      </div>
      <p class="tips" v-if="showCounter">因赔率随时变动，请与终端机赔率核对，最终结果以出票为准！</p>
    </div>
  </van-overlay>
  <!-- 奖金评测 - 弹出层 -->
  <van-popup v-model:show="showTestPop" position="bottom" :style="{ maxHeight: '80%', background: 'transparent' }"
    :overlay-style="{ background: 'rgba(0, 0, 0, 0.3)' }">
    <div class="pop bottomPop">
      <div class="popTit">奖金评测<van-icon name="cross" color="#bbb" class="closeBtn"
          @click="showTestPop = false" /></div>
      <table v-if="dans.length>0">
        <thead>
          <tr>
            <th width="24%">胆命中</th>
            <th width="24%">拖命中</th>
            <th width="24%">最低奖金</th>
            <th width="4%">-</th>
            <th width="24%">最高奖金</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, i) in bonusTestList" :key="i">
            <td>{{ item.danNum }}</td>
            <td>{{ item.tuoNum }}</td>
            <td>{{ item.minMoney?.toFixed(2) }}</td>
            <td>-</td>
            <td class="max">{{ item.maxMoney?.toFixed(2) }}</td>
          </tr>
        </tbody>
      </table>
      <table v-else>
        <thead>
          <tr>
            <th width="30%">命中场次</th>
            <th width="35%">最低奖金</th>
            <th width="5%">-</th>
            <th width="35%">最高奖金</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, i) in bonusTestList" :key="i">
            <td>{{ item.hitnum }}</td>
            <td>{{ item.minBouns?.toFixed(2) }}</td>
            <td>-</td>
            <td class="max">{{ item.maxBouns?.toFixed(2) }}</td>
          </tr>
        </tbody>
      </table>
      <p class="tips" v-if="showCounter">因赔率随时变动，请与终端机赔率核对，最终结果以出票为准！</p>
    </div>
  </van-popup>
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { useCalcStore } from "@/stores";
import { useRouter } from 'vue-router'
import { oddsHeaderCodeFootball } from "@/utils/data";
import { chuanList, chuanMoreList } from '@/utils/chuan'
import { Football, countMaxOdds, wfs } from '@/utils/football'
import { Basktball } from '@/utils/basktball'

const calc = useCalcStore() // 竞猜store
const { orderData, raceColor, isInShares } = storeToRefs(calc)

const router = useRouter()
const emit = defineEmits(['changeType']);
const props = defineProps({
    type: {
        type: String,
        default: ''
    }
})
const multiNum = ref(1) // 倍数
const showChuanPop = ref(false)
const showTestPop = ref(false)
const selectedTab = ref(0) // 0过关方式 1设胆
const isDg1 = ref(false); // 所选玩法全部是单关
const chuanFilter = ref([]);
const chuanMoreFilter = ref([]);
const gG = reactive({selectChuans: [], firstText: ''});
const dans = ref([]); // 选中的胆
const maxBonus = ref(0); // 预计最高奖金
const zhuNum = ref(0); //注数
const bonusTestList = ref([]); // 奖金评测数据
let counter = null;

const vals = computed(() => Object.values(orderData.value).sort((a, b)=>{
    const aNum = Number(a[0].weekNum.charAt(0) == '0' ? ('7' + a[0].weekNum.slice(1)) : a[0].weekNum),
        bNum = Number(b[0].weekNum.charAt(0) == '0' ? ('7' + b[0].weekNum.slice(1)) : b[0].weekNum);
    return aNum - bNum;
}))
const betAmt = computed(() => zhuNum.value * 2 * multiNum.value)

watch(() => props.type, () => counter = null) // 切换篮球或足球
watch(() => vals.value, (newVal)=>{
    // 足球数据基于orderData, 篮球数据基于raceColor
    let len = 8; // 最高8串
    let dg = true, has4 = false, has6 = false;
    const matchChoose = {}, choose = {};
    for (const match of vals.value) { // 循环比赛
        const firstM = match[0];
        const flag = firstM.weekNum;
        choose[flag] = {};
        for (const pm of match) { // 循环具体选择的玩法块
            if (props.type === 'z'){
                if (['crs', 'hafu'].includes(pm.type)) has4 = true; // 比分和半全场
                if (pm.type == 'ttg') has6 = true; // 总进球
                // 足球需要拼出choose数据
                const wf = wfs[pm.type];
                if (!wf) return;
                const idx = Number((wf == '3') ? '4' : (wf == '4' ? '3' : wf)); // 转化玩法代码
                const oddinfo = oddsHeaderCodeFootball[idx].find(item => item.nameCode == pm.play);
                if (oddinfo) {
                    const { nameIndex, namePy } = oddinfo;
                    if (!choose[flag][wf]) choose[flag][wf] = {}
                    choose[flag][wf][nameIndex] = { sp: Number(pm.odds), xx: namePy };
                }
            }else{
                if (pm.type == 'wnm') has4 = true; // 胜分差
            }
            if (pm.single == 0) dg = false;
        }
        // const sortArr = match.sort((a, b) => Number(a.odds) - Number(b.odds));
        if (props.type === 'z') {
            // 足球需要拼接 matchChoose 数据
            matchChoose[flag] = countMaxOdds(flag, firstM.polygoal, firstM.matchId, choose[flag])
        }
    }
    if (has4 && has6) {
        len = 4
    } else if (has4) {
        len = 4
    } else if (has6) {
        len = 6
    }
    len = (len > newVal.length) ? newVal.length : len;
    isDg1.value = dg;
    chuanFilter.value = chuanList.filter(item => {
        return dg ? (item.c <= len) : (item.c != 1 && item.c <= len);
    })
    chuanMoreFilter.value = chuanMoreList.filter(item => item.c <= len);
    // 默认选择最高的串关方式
    const cLen = chuanFilter.value.length;
    if (cLen > 0) {
        const { v, t } = chuanFilter.value[cLen - 1];
        gG.selectChuans = [v];
        gG.firstText = t;
    }
    if (props.type === 'z'){
        if (!counter) {
            // 创建足球实例
            counter = new Football(gG.selectChuans, choose, matchChoose, multiNum.value);
        } else {
            // 更新足球选择的数据
            counter.updateChoose(gG.selectChuans, choose, matchChoose);
        }
    }else{
        if (!counter){
            counter = new Basktball(gG.selectChuans, Object.values(raceColor.value), multiNum.value);
        }else{
            counter.updateChoose(gG.selectChuans, Object.values(raceColor.value));
        }
    }
    maxBonus.value = counter.getMaxBonus();
    zhuNum.value = counter.getZhuShu();
},{deep: true, immediate: true})

const isDg1Tips = computed(() => {
    const len = vals.value.length;
    let txt = len;
    if (len === 0) {
        txt = '请先选择比赛'
    } else if (len === 1 && !isDg1.value) {
        txt = '请再选择一场比赛'
    }
    return txt
})
const showCounter = computed(() => { // 是否展示计算器
    const len = vals.value.length;
    return (len == 1 && isDg1.value) || (len > 1);
})
const canOpt = computed(() => { // 是否展示奖金优化
    // 奖金优化不支持定胆、M串N
    const evt = showCounter.value && vals.value.length <= 15 && zhuNum.value <= 500 && gG.selectChuans.length > 0 && dans.value.length == 0 && !gG.selectChuans.some(item => item.split('_')[1] !== '1');
    return evt;
})
// 更改倍数
function changeMulti(type){
    if(type=='-'){
        if (multiNum.value == 1) return
        multiNum.value--
    } else if (type == '+'){
        multiNum.value++
    }
    maxBonus.value = counter.updateMult(multiNum.value);
    if (showTestPop.value) showTestPop.value = false;
}
// 重置页面数据
function resetData() {
  calc.saveData({})
  calc.changeOdds(1)
}
// 底部重选按钮 情况数据
function goResetData() {
  showToast({
    message: '数据重置中...',
    duration: 5000,
    overlay: true
  })
  const { type } = props;
  emit('changeType','')
  setTimeout(() => {
    resetData()
    emit('changeType', type)
    closeToast()
  }, 0)
}
// 底部确定按钮 页面跳转
function gotoPoster() {
    const { parame, possibleComb } = counter.bonusOpt(vals.value);
    // 组合数据后存储起来
    sessionStorage.setItem('optData', JSON.stringify(parame));
    sessionStorage.setItem('possibleComb', JSON.stringify(possibleComb));
    const name = props.type === 'z' ? 'footballVerify' : 'basketballVerify';
    const cg = gG.selectChuans.join(',');
    router.push({ path: '/calcResult', query: { name, allPrice: betAmt.value, cg, multiNum: multiNum.value } })
}
// 打开过关弹窗
function openGgHandle() {
    showTestPop.value = false
    showChuanPop.value = !showChuanPop.value
}
// 打开奖金优化弹窗
function openBonusTest() {
    if (gG.selectChuans.length === 0 || Number(maxBonus.value) === 0) return;
    showChuanPop.value = false
    showTestPop.value = !showTestPop.value
    if (dans.value.length>0){
        bonusTestList.value = counter.danTest();
    }else{
        bonusTestList.value = counter.bonusTest();
    }
}
// 选择串关方式
function chuanHandle(v){
    const findIndex = gG.selectChuans.indexOf(v);
    if (findIndex>-1){
        gG.selectChuans.splice(findIndex, 1);
    }else{
        if (gG.selectChuans.length == 5) return showToast('组合过关方式不能超过5个');
        gG.selectChuans.push(v)
    }
    if (gG.selectChuans.length > 0){
        // 从串关方式中获取
        const ncx = gG.selectChuans[0];
        const data = ncx.split('_')[1] == '1' ? chuanFilter.value : chuanMoreFilter.value;
        gG.firstText = data.find(item => item.v == ncx).t;
    }else{
        gG.firstText = '过关';
        dans.value = [];
    }
    // 更新实例的串关数据
    counter.updateChuan(gG.selectChuans)
    if (dans.value.length > 0 && (dans.value.length > counter.selChuanArr[0] || counter.selChuanArr[1] !== 0)){
        // 设置了胆，并且胆的数量大于最小过关场数 重置胆
        // 选择的胆里面有M串N的多串形式也会 重置胆
        dans.value = [];
        counter.setDan([]);
    }
    maxBonus.value = counter.getMaxBonus();
    zhuNum.value = counter.getZhuShu();
}
// 选择胆
function danHandle(weekNum){
  const findIndex = dans.value.indexOf(weekNum);
  if (findIndex>-1){
    dans.value.splice(findIndex, 1);
  }else{
    const minGg = counter.selChuanArr;
    if (dans.value.length == minGg[0]) return showToast('设胆个数不能超过最小过关场数');
    if (minGg[1] !== 0) return showToast('设胆不支持M串N的多串过关方式');
    dans.value.push(weekNum);
  }
  counter.setDan(dans.value);
  maxBonus.value = counter.getMaxBonus();
  zhuNum.value = counter.getZhuShu();
}
// 奖金优化
function bonusOpt() {
  const { parame, possibleComb } = counter.bonusOpt(vals.value);
  // 组合数据后存储起来
  sessionStorage.setItem('optData', JSON.stringify(parame));
  sessionStorage.setItem('possibleComb', JSON.stringify(possibleComb));
  // 再跳转到优化页面
  router.push('/bonusOptimize');
}
</script>

<style lang='less' scoped>
.tips {
    line-height: 24px;
    font-size: 12px;
    text-align: center;
    background-color: #fff4ee;
    color: #fe673a;
}
.pop{
    width: 100%;
    // padding-bottom: 216px;
    padding-bottom: 92px;
    color: #1D2129;
    position: relative;
    background: #fff;
}
.fixedBottomPop{
    position: fixed;
    bottom: 0;
    left: 0;
    // max-height: 80%;
    .closeBtn {
        position: absolute;
        top: -33px;
        left: 50%;
        transform: translate(-50%, 0);
        display: block;
        margin: 0 auto 9px;
        padding: 0;
        width: 27px;
        border-radius: 50%;
        font-size: 26px;
    }
    .scrollArea{
        max-height: 50vh;
        overflow: auto;
        -webkit-overflow-scrolling: touch;
    }
    .tabs {
        width: 100%;
        display: flex;
    }

    .tab {
        width: 374px;
        height: 38px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
        border: 1px solid #fe673a;

        &.act {
            font-size: 16px;
            color: #fff;
            background: #fe673a;
        }
    }

    .ggWay {
        display: flex;
        flex-wrap: wrap;
        color: #1D2129;
        font-size: 13px;
        padding: 8px 11.5px;
    }

    .gg {
        width: 80px;
        height: 34px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        background: #f2f2f2;
        margin: 4px;
        overflow: hidden;

        &.act {
            border: 1px solid #fe673a;
            position: relative;
            background: transparent;

            &::after {
                content: '';
                width: 17px;
                height: 17px;
                background-image: url('~@/assets/image/shopColorTools/raceColor/selected.png');
                background-size: contain;
                position: absolute;
                right: -1px;
                bottom: -1px;
            }
        }
    }

    .title {
        width: 100%;
        font-size: 14px;
        line-height: 22px;
        margin: 8px 0;
        padding: 0 4px;
        .tip{
            font-size: 12px;
            color: #ccc;
            margin-left: 10px;
        }
    }

    .setDanList {
        // max-height: calc(50vh - 0.76rem);
        // max-height: 4rem;
        .li {
            display: flex;
            align-items: center;
            min-height: 61px;
            border-bottom: 1px solid #e9e9e9;
            padding: 10px 10px 10px 0;

            &:last-child {
                border: none;
            }

            .delete {
                width: 40px;
                height: 61px;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 16px;
                color: #c5c5c5;
                flex-shrink: 0;
            }

            .matchDetail {
                flex: 1;
                max-width: 339px;
                padding-left: 10px;
                // max-width: 5.98rem;

                .tit {
                    color: #4E5969;
                    font-size: 12px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                --van-tag-padding: 3px 10px;
                --van-tag-font-size: 10px;
                --van-tag-line-height: 16px;

                :deep(.van-tag) {
                    margin: 4px 4px 4px 0;
                }
            }

            .setup {
                flex-shrink: 0;
                width: 26px;
                height: 26px;
                background: transparent;
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 1px solid #f96235;
                color: #f96235;

                &.act {
                    background: #f96235;
                    color: #fff;
                }
            }
        }
    }
}
.bottomPop{
    // padding-top: .76rem;
    position: relative;
    .popTit{
        text-align: center;
        line-height: 44px;
        height: 44px;
        font-size: 16px;
        position: relative;
        .closeBtn{
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
        }
    }
    table{
        width: 100%;
        table-layout: fixed;
        thead tr{
          background: #f2f2f2;
        }
        tr{
          width: 100%;
          &:nth-child(2n){
              background: #f2f2f2;
          }
        }
        td,th{
            height: 28px;
            text-align: center;
            font-size: 14px
        }
        td{
            color: #4E5969;
        }
        .max{
            color: #FE673A;
        }
    }
}
.footbox {
    position: fixed;
    z-index: 5000;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    box-shadow: 1px 0 5px #ccc;
    .amt {
        color: #FE673A;
    }
    .selectBar{
        display: flex;
        align-items: center;
        background: #f2f2f2;
        height: 40px;
        font-size: 12px;
        color: #1D2129;
        padding: 0 16px;
        .block{
            display: flex;
            align-items: center;
            margin-left: 16px;
        }
        .label{
            margin-right: 4px;
        }
        .ggBox{
            width: 50px;
            height: 20px;
            border-radius: 2px;
            border: 1px solid #e7e7e7;
            background: #ffffff;
            font-size: 12px;
            color: #1D2129;
            display: flex;
            justify-content: center;
            align-items: center;
            :deep(.van-icon-play){
                transform: rotate(90deg);
            }
        }
        .multiBox{
            width: 115px;
            height: 20px;
            display: flex;
            .plus, .sub {
                width: 20px;
                height: 20px;
                border: 1px solid #e7e7e7;
                background: #ffffff;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 14px;
            }
            .sub{
                border-radius: 0.04px 0 0 2px;
            }
            .plus{
                border-radius: 0 2px 2px 0;
            }
            .multIpt{
                width: 25px;
                height: 20px!important;
                border-top: 1px solid #e7e7e7;
                border-bottom: 1px solid #e7e7e7;
                padding: 0!important;
                --van-cell-line-height: 20px;
                :deep(.van-field__control){
                    text-align: center;
                    font-size: 12px;
                    color: #1D2129;
                }
            }
        }
    }
    .counterBar{
        width: 100%;
        height: 52px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 16px;
        --van-button-default-height: 32px;
        --van-button-default-line-height: 32px;
        --van-button-normal-font-size: 14px;
        :deep(.van-button) {
            margin-left: 6px;
        }
        .left p{
            color: #1D2129;
            font-size: 14px;
            line-height: 15px;
        }
        .fz20{
            font-size: 10px!important;
        }
        .maxBonus{
            text-decoration: underline;
        }
        .btns{
            display: flex;
            align-items: center;
        }
        .bonusOpt{
            font-size: 13px;
            color: #F96235;
        }
    }
    .confirm {
        height: 50px;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;
        position: relative;

        .left {
            width: 72px;
            height: 31px;
            border: 1px solid #fe0000;
            color: #fe0000;
            font-size: 15px;
            border-radius: 2.5px;
            text-align: center;
            line-height: 31px;
        }

       .center{
            position: absolute;
            transform: translate(-50%, -50%);
            left: 50%;
            top: 50%;
            font-size: 16px;
            color: #333;
            text-align: center;
            span {
                margin: 0 5px;
                color: #fe0000;
            }
        }

        .right {
            width: 81px;
            height: 31px;
            background: #fe0000;
            color: #fff;
            text-align: center;
            line-height: 30px;
            border-radius: 2.5px;
            font-size: 16px
        }
    }
}
</style>
